package com.kun.service;

import com.kun.common.Constants;
import com.kun.common.Result;
import com.kun.entity.Course;
import com.kun.exception.MyServiceException;
import com.kun.mapper.CourseMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CourseServiceImpl implements CourseService {

    @Autowired
    private CourseMapper courseMapper;

    @Override
    public Result addCourse(Course course) {
        if (course.getId()==null){
            if (StringUtils.isEmpty(course.getName())){
                throw new MyServiceException(Constants.CODE_500,"业务异常,name属性不能为空");
            }else{
                HashMap<String, Object> map = new HashMap<>();
                map.put("name",course.getName());
                if (courseMapper.selectAllCourses(map).size()>1){
                    throw  new MyServiceException(Constants.CODE_600,"数据库异常,name属性重复");
                } else{
                    courseMapper.addCourse(course);
                }
            }
        }else{
            courseMapper.updateCourse(course);
        }
        return Result.success();

    }

    @Override
    public int deleteCourse(Integer id) {
        return courseMapper.deleteCourse(id);
    }

    @Override
    public int updateCourse(Course course,Map map) {
        return courseMapper.updateCourse(course);
    }

    @Override
    public List<Course> selectAllCourses(Map map) {
        if (map.containsKey("pageIndex") && map.containsKey("pageSize")){
            Integer pageIndex = (Integer) map.get("pageIndex");
            Integer pageSize= (Integer) map.get("pageSize");
            pageIndex=pageSize*(pageIndex-1);
            map.replace("pageIndex",pageIndex);
        }
        return courseMapper.selectAllCourses(map);
    }
}
